﻿@attribute [JSCustomElement]
@inject I18n I18n

<MTextField @bind-Value="_value"
            BackgroundColor="#F6F8FD"
            Class="search-input rounded-lg"
            Placeholder="@I18n.T("Search")"
            OnInput="OnSearch"
            TValue="string"
            Clearable
            ClearIcon="mdi-close-circle"
            HideDetails="true"
            OnClearClick="InitDataAsync"
            Filled
            Rounded
            Dense
            Height="48">
    <PrependInnerContent>
        <MIcon Class="emphasize2-color">mdi-magnify</MIcon>
    </PrependInnerContent>
</MTextField>

<MRow Class="mt-9">
    @foreach (var component in _allComponents)
    {
        <MCol Md="4" Sm="12" Class="justify-center">
            <MCard Href="@component.Href" Class="rounded-2" Elevation="0" Color="#F6F8FD" Height="200" Width="300">
                <div class="d-flex justify-center align-center" style="height: 100%; width: 100%;">
                    <img class="rounded-0"
                         src="@($"https://cdn.masastack.com/stack/doc/blazor/all-components/{component.Title}.png")"
                         onerror="this.src='_content/Masa.Blazor.Docs/img/default-img.png'" />
                </div>
            </MCard>
            <h3 class="mt-2">@I18n.T(component.Title)</h3>
            <div class="mt-1">@I18n.T($"all-components.{component.Title}")</div>
        </MCol>
    }
</MRow>

@code {
    string _value = string.Empty;
    List<NavItem> _allComponents = new();
    List<NavItem> _originalAllComponents = new();

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            await InitDataAsync();            

            StateHasChanged();
        }
    }

    async Task InitDataAsync()
    {
        _allComponents = await DocService.GetAllConponentsTileAsync();

        if (_allComponents.Any())
        {
            _originalAllComponents = new List<NavItem>(_allComponents.ToArray());
        }
    }

    void OnSearch()
    {
        if (string.IsNullOrEmpty(_value))
        {
            _allComponents = _originalAllComponents;
        }
        else
        {
            _allComponents = _originalAllComponents.Where(nav => I18n.T(nav.Title).Contains(_value, StringComparison.InvariantCultureIgnoreCase)).ToList();
        }
    }
}